package com.etc.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.etc.entity.ShopcObj;
import com.etc.util.AjaxUploadResponse;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

/**
 * Servlet implementation class AjaxOrderServlet
 */
@WebServlet("/ajaxorder.do")
public class AjaxOrderServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;


	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		response.setContentType("application/json;charset=utf-8");
		String json = request.getParameter("shopc");
		System.out.println(json);
		
		Gson gson = new Gson();

		// TypeToken String=>java对象
		List<ShopcObj> list = gson.fromJson(json, new TypeToken<List<ShopcObj>>() {
		}.getType());
		list.forEach(System.out::println);
        //订单中商品信息(goodsid goodname price  count)
		request.getSession().setAttribute("list", list);
		
		//计算当前订单的总金额
		double ztotal = 0;
		for (ShopcObj shopcObj : list) {
			ztotal += shopcObj.getTotal();
		}
		//总金额 存储到session
		request.getSession().setAttribute("ztotal", ztotal);
		// 处理购物车完成下单功能
		PrintWriter out = response.getWriter();

		AjaxUploadResponse aur = new AjaxUploadResponse();
		

		if (list.size() != 0) {
			aur.setMsg("操作成功!");
			aur.setCode(0);
		} else {
			aur.setMsg("操作失败!");
			aur.setCode(1);
		}

		//
		String str = gson.toJson(aur);

		out.print(str);
		out.close();

	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

	

}
